import { defineStore } from 'pinia'

// 用户状态管理
export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null, // 用户信息
    isLoggedIn: false, // 登录状态
    addresses: [], // 收货地址列表
    defaultAddress: null // 默认收货地址
  }),
  getters: {
    // 获取用户ID
    userId: (state) => state.userInfo?.id,
    // 获取用户昵称
    userName: (state) => state.userInfo?.nickname || '游客',
    // 获取用户头像
    userAvatar: (state) => state.userInfo?.avatar || '/assets/default-avatar.png'
  },
  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      this.isLoggedIn = true
    },
    
    // 登录（模拟）
    async login(credentials) {
      try {
        // 这里应该调用后端API进行登录
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        // 模拟登录成功后返回的用户信息
        const mockUserInfo = {
          id: 'USER' + Date.now(),
          nickname: 'AI商城用户',
          avatar: '/assets/default-avatar.png',
          phone: credentials.phone || '13800138000',
          email: 'user@aismartshop.com',
          createTime: '2023-01-01'
        }
        
        this.setUserInfo(mockUserInfo)
        // 登录成功后加载地址列表
        await this.loadAddresses()
        
        return { success: true, userInfo: mockUserInfo }
      } catch (error) {
        console.error('登录失败:', error)
        return { success: false, message: '登录失败，请重试' }
      }
    },
    
    // 登出
    logout() {
      this.userInfo = null
      this.isLoggedIn = false
      this.addresses = []
      this.defaultAddress = null
    },
    
    // 设置收货地址列表
    setAddresses(addresses) {
      this.addresses = addresses
      // 设置默认地址
      const defaultAddr = addresses.find(addr => addr.isDefault)
      if (defaultAddr) {
        this.defaultAddress = defaultAddr
      }
    },
    
    // 加载收货地址列表（模拟）
    async loadAddresses() {
      try {
        // 这里应该调用后端API获取地址列表
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 800))
        
        // 模拟地址列表数据
        const mockAddresses = [
          {
            id: 'ADDR001',
            consignee: '张三',
            phone: '13800138000',
            province: '广东省',
            city: '深圳市',
            district: '南山区',
            detail: '科技园南区8栋',
            isDefault: true
          },
          {
            id: 'ADDR002',
            consignee: '李四',
            phone: '13900139000',
            province: '广东省',
            city: '广州市',
            district: '天河区',
            detail: '天河路385号',
            isDefault: false
          }
        ]
        
        this.setAddresses(mockAddresses)
        return { success: true, addresses: mockAddresses }
      } catch (error) {
        console.error('加载地址失败:', error)
        return { success: false, message: '加载地址失败，请重试' }
      }
    },
    
    // 添加收货地址（模拟）
    async addAddress(address) {
      try {
        // 这里应该调用后端API添加地址
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 800))
        
        // 生成地址ID
        const newAddress = {
          ...address,
          id: 'ADDR' + Date.now()
        }
        
        // 如果设置为默认地址，取消其他地址的默认状态
        if (address.isDefault) {
          this.addresses.forEach(addr => {
            addr.isDefault = false
          })
          this.defaultAddress = newAddress
        }
        
        this.addresses.push(newAddress)
        return { success: true, address: newAddress }
      } catch (error) {
        console.error('添加地址失败:', error)
        return { success: false, message: '添加地址失败，请重试' }
      }
    },
    
    // 更新收货地址（模拟）
    async updateAddress(addressId, address) {
      try {
        // 这里应该调用后端API更新地址
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 800))
        
        const index = this.addresses.findIndex(addr => addr.id === addressId)
        if (index !== -1) {
          // 如果设置为默认地址，取消其他地址的默认状态
          if (address.isDefault) {
            this.addresses.forEach(addr => {
              addr.isDefault = false
            })
            this.defaultAddress = { ...address, id: addressId }
          }
          
          this.addresses[index] = { ...address, id: addressId }
          return { success: true }
        } else {
          return { success: false, message: '地址不存在' }
        }
      } catch (error) {
        console.error('更新地址失败:', error)
        return { success: false, message: '更新地址失败，请重试' }
      }
    },
    
    // 删除收货地址（模拟）
    async deleteAddress(addressId) {
      try {
        // 这里应该调用后端API删除地址
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 800))
        
        const index = this.addresses.findIndex(addr => addr.id === addressId)
        if (index !== -1) {
          // 如果删除的是默认地址，设置第一个地址为默认
          if (this.addresses[index].isDefault && this.addresses.length > 1) {
            this.addresses[0].isDefault = true
            this.defaultAddress = this.addresses[0]
          } else if (this.addresses.length === 1) {
            this.defaultAddress = null
          }
          
          this.addresses.splice(index, 1)
          return { success: true }
        } else {
          return { success: false, message: '地址不存在' }
        }
      } catch (error) {
        console.error('删除地址失败:', error)
        return { success: false, message: '删除地址失败，请重试' }
      }
    },
    
    // 设置默认地址
    async setDefaultAddress(addressId) {
      try {
        // 这里应该调用后端API设置默认地址
        // 模拟API调用延迟
        await new Promise(resolve => setTimeout(resolve, 800))
        
        const address = this.addresses.find(addr => addr.id === addressId)
        if (address) {
          // 取消其他地址的默认状态
          this.addresses.forEach(addr => {
            addr.isDefault = addr.id === addressId
          })
          
          this.defaultAddress = address
          return { success: true }
        } else {
          return { success: false, message: '地址不存在' }
        }
      } catch (error) {
        console.error('设置默认地址失败:', error)
        return { success: false, message: '设置默认地址失败，请重试' }
      }
    }
  },
  // 持久化配置
  persist: {
    key: 'ai-shop-user',
    storage: localStorage,
    paths: ['userInfo', 'isLoggedIn', 'addresses', 'defaultAddress']
  }
})